package com.metroinfo.workers.selector;

import java.io.*;
import java.nio.channels.*;

import com.metroinfo.infrastructure.MainDataStructure;
import com.metroinfo.workers.ChannelIO;

/**
 * A Runnable class which sits in a loop accepting SocketChannels,
 * then registers the Channels with the read/write Selector.
 *
 * @author Mark Reinhold
 * @author Brad R. Wetmore
 * @version 1.4, 10/01/12
 */
public class Acceptor implements Runnable {

    private ServerSocketChannel ssc;
    private Dispatcher d;
    
    private MainDataStructure mds;

    public Acceptor(ServerSocketChannel ssc, Dispatcher d, MainDataStructure mds) {
	this.ssc = ssc;
	this.d = d;
	this.mds = mds;
    }

    public void run() {
	for (;;) {
	    try {
		SocketChannel sc = ssc.accept();

		ChannelIO cio = ChannelIO.getInstance(
			sc, false /* non-blocking */);

		RequestHandler rh = new RequestHandler(cio, mds);

		d.register(cio.getSocketChannel(), SelectionKey.OP_READ, rh);

	    } catch (IOException x) {
		x.printStackTrace();
		break;
	    }
	}
    }
}
